package org.deng.vertx.common.util;




import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * Created by DengLibin on 2017/5/27.
 * Aes加解密 工具
 */
public class AesUtil {

    //Base64编解码器
    private static final Base64.Decoder decoder = Base64.getDecoder();
    private static final Base64.Encoder encoder = Base64.getEncoder();
    //加密算法
    private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param aesKey 密钥
     * @param srcStr 加密的字符串
     * @return 加密后的base64字符串
     */
    public static String encrypt(String aesKey,String srcStr){

        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
            SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8),"AES");
            cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
            return  encoder.encodeToString(cipher.doFinal(srcStr.getBytes(StandardCharsets.UTF_8)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param aesKey 密钥
     * @param str 加密后的base64字符串
     * @return 解密后的字符串
     */
    public static String decrypt(String aesKey,String str)  {
        try {
            Cipher cipher  = Cipher.getInstance(ALGORITHM_STR);
            SecretKeySpec secretKeySpec = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8),"AES");
            cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
            return new String(cipher.doFinal(decoder.decode(str)), StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加解密测试
     * @param args
     */
    public static void  main(String[] args){
        String key = "ji8Alx91c8sKOwsK";
        String s = encrypt(key, "{\"username\": \"admintest\", \"areaname\": \"北京市\"}");
        System.out.println(s);
        System.out.println(decrypt(key, s));

    }

}
